package autoUpdater.helper;

import java.io.InputStream;
import java.security.KeyStore;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

public class OwnTrustManager implements X509TrustManager {

	private X509TrustManager trustManager = null;
	

	public OwnTrustManager() throws Exception {
		reloadTrustManager();
	}

	@Override
	public void checkClientTrusted(X509Certificate[] chain, String authType)
			throws CertificateException {
		trustManager.checkClientTrusted(chain, authType);
	}

	@Override
	public void checkServerTrusted(X509Certificate[] chain, String authType)
			throws CertificateException {

		trustManager.checkServerTrusted(chain, authType);

	}

	@Override
	public X509Certificate[] getAcceptedIssuers() {
		X509Certificate[] issuers = trustManager.getAcceptedIssuers();
		return issuers;
	}

	//
	private void reloadTrustManager() throws Exception {

		// load keystore from specified cert store (or default)
		KeyStore ts = KeyStore.getInstance(KeyStore.getDefaultType());

		InputStream in = Thread.currentThread().getContextClassLoader()
				.getResourceAsStream("autoUpdater/helper/certs");
		try {
			ts.load(in, "testtest".toCharArray());
		} finally {
			in.close();
		}

		// initialize a new TMF with the ts we just loaded
		TrustManagerFactory tmf = TrustManagerFactory
				.getInstance(TrustManagerFactory.getDefaultAlgorithm());
		tmf.init(ts);

		// acquire X509 trust manager from factory
		TrustManager tms[] = tmf.getTrustManagers();
		for (int i = 0; i < tms.length; i++) {
			if (tms[i] instanceof X509TrustManager) {
				trustManager = (X509TrustManager) tms[i];
				return;
			}
		}

		throw new NoSuchAlgorithmException(
				"No X509TrustManager in TrustManagerFactory");
	}

}